#!/usr/bin/ruby

require 'thread'

READ_BUF_SIZE = 1024

class Svr
  attr_accessor :w
  
  def initialize
    @work_threads = {}
  end
  
  def bind(clt)
    t = working_loop(clt,*IO.pipe)
    @work_threads[clt.name] = t
    #如果没有延时则返回的t[:w]为nil
    sleep 0.1
    t[:w]
  end
  
  #删除已死的work_thread
  def clear_dead_thread
    @work_threads.delete_if {|k,t|!t.alive?}
  end
  
  def working_loop(clt,r,w)
    Thread.new(clt,r,w) do |clt,r,w|
      t = Thread.current
      t[:clt] = clt
      t[:w] = w
      clt.w.write("hello #{clt}\n")
      loop do
        begin
          sleep 0.1
          str = r.read_nonblock READ_BUF_SIZE
          str.chop!.force_encoding("utf-8")
          if str =~ /quit/i
            clt.w.write("byebye...\n")
            break
          end
          #puts "recv from #{clt} : #{str}:#{str.encoding}"
          clt.w.write(str.reverse + " #{Time.now}\n")
        rescue IO::EAGAINWaitReadable =>e
          nil
        end
      end
    end
  end
  
  private :working_loop
end

class Clt
  attr_reader :name,:w
  
  def initialize(name)
    @name = name
    @r,@w = IO.pipe
  end
  
  def connect(svr)
    @svr_w = svr.bind(self)
  end
  
  def puts(msg)
    @svr_w.write(msg)
  end
  
  def gets
    @r.read_nonblock READ_BUF_SIZE
  rescue IO::EAGAINWaitReadable =>e
    nil
    #retry
  end
  
  def to_s
    "#{@name}"
  end
end

#=begind
svr = Svr.new
clt = Clt.new("ks")
clt.connect svr

loop do
  until str = clt.gets
    
  end
  puts str
  break if str =~ /bye/i
  clt.puts gets
end
#=end
